package org.jeecg.modules.vx.student.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.jeecg.modules.vx.student.entity.Student;
import org.jeecg.modules.vx.student.mapper.StudentMapper;
import org.jeecg.modules.vx.student.service.IStudentService;
import org.jeecg.modules.vx.student.util.EmptyUtil;
import org.jeecg.modules.vx.student.util.HttpUtil;
import org.jeecg.modules.vx.student.util.WxEnumUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author li
 * @since 2021-08-15
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    @Resource
    private StudentMapper studentMapper;
    @Override
    public Student login(String code) {
        //把请求参数封装成map
        Map<String, String> param = new HashMap<>();
        param.put("appid", WxEnumUtil.APPID.getName());
        param.put("secret", WxEnumUtil.APPSECRET.getName());
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        Student student=new Student();
        try {
            //请求的地址
            String result= HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session",param);
            //判断是否存在appid
            JSONObject jsonObject= JSON.parseObject(result);
            String openid= jsonObject.getString("openid");
            System.out.println(result);
            //不存在openid
            if (EmptyUtil.isEmptyStr(openid)) {
                return null;
            }else {
                //存在openid就需要查询这个openid在数据中是否存在
                QueryWrapper<Student>queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("student_openid",openid);
                 student = studentMapper.selectOne(queryWrapper);
                //openid在数据库中存在
                if (student!=null){
                    //数据库中存在openid，就直接将该用户返回给前端
                    return student;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return student;
    }


}
